package com.agent.action.client;

import com.agent.action.entity.DifyWorkFlowEntity;
import com.agent.action.entity.PauseEntity;
import com.agent.action.interfaces.BuilderInterface;
import com.agent.action.interfaces.WorkFlowClient;
import com.agent.action.param.FlowPauseParam;
import com.agent.action.param.PauseParam;
import com.agent.commons.utils.JacksonUtil;
import com.alibaba.fastjson.JSON;
import feign.Client;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import reactor.core.publisher.Flux;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * Dify工作流调用客户端
 */
@Data
@Slf4j
public class DifyWorkClient<T> implements WorkFlowClient<T>, BuilderInterface<DifyWorkClient<T>> {
    /**
     * Dify工作流uri
     */
    private String uri;
    /**
     * Dify具体请求url
     */
    private String url;
    /**
     * Dify工作流key
     */
    private String key;
    /**
     * WebClient
     */
    private WebClient webClient;

    /**
     * 设置请求url
     * @param url
     * @return
     */
    @Override
    public DifyWorkClient<T> url(String url){
        this.url = url;
        return this;
    }
    /**
     * 设置key
     * @param key
     * @return
     */
    @Override
    public DifyWorkClient<T> key(String key){
        this.key = key;
        return this;
    }

    /**
     * 构建客户端
     * @param uri
     * @return
     */
    @Override
    public DifyWorkClient<T> builder(String uri){
        this.webClient=WebClient.builder()
                .baseUrl(uri+url)
                .defaultHeader("Content-Type","application/json")
                .defaultHeader("Authorization","Bearer "+key)
                .build();
        return this;
    }

    /**
     * 流式响应
     * @param difyWorkFlowEntity
     * @return
     */
    @Override
    public Flux<String> stream(DifyWorkFlowEntity<T> difyWorkFlowEntity){
        String strDify = JSON.toJSONString(difyWorkFlowEntity);
        log.info("DifyWorkClient:{}", strDify);
        return webClient.post()
                .uri("/run")
                .bodyValue(strDify)
                .retrieve()
                .bodyToFlux(String.class);
    }

    /**
     * 暂停工作流交互
     * @param flowpauseParam
     */
    @Override
    public void pause(PauseParam flowpauseParam) {
        PauseEntity pauseEntity = new PauseEntity();
        pauseEntity.setUser(flowpauseParam.getUserId());
        log.info("PauseEntity:{}",  JacksonUtil.writeValueAsString(pauseEntity));
        webClient.post()
                .uri("/tasks/" + flowpauseParam.getTaskId() + "/stop")
                .bodyValue(JSON.toJSONString(pauseEntity))
                .retrieve()
                .bodyToMono(String.class)
                .subscribe();
    }
}
